package com.hq.talk.view.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.hq.lib_comview.common.ClickCounter;
import com.hq.lib_comview.common.code.IntentKey;
import com.hq.lib_comview.common.utils.LogUtils;
import com.hq.lib_comview.common.utils.StringUtils;
import com.hq.lib_comview.view.scprogress.SVProgressHUD;
import com.hq.talk.R;
import com.hq.talk.common.BaseEvent;
import com.hq.talk.common.ConstantTag;
import com.hq.talk.common.Session;
import com.hq.talk.model.UserInfoModel;
import com.hq.talk.presenter.impl.UserPresenter;
import com.hq.talk.view.base.BaseCommAty;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.litesuits.common.utils.HexUtil;
import com.litesuits.common.utils.MD5Util;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 描述 ：登录界面
 * 作者 ：hq
 * 时间 ：2017/8/5 01:01
 */
public class LoginAty extends BaseCommAty {

    @BindView(R.id.id_login_phone_edit)
    EditText mEditPhone;
    private String mSavePhone;
    @BindView(R.id.id_login_pw_edit)
    EditText mEditPw;
    private String mSavePw;

    private UserInfoModel model;
    private boolean isRegister;

    @Nullable
    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_login, null, false));
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initPresenter() {
        presenter = new UserPresenter();
    }

    @Override
    public void initView() {
        setTitleText(getString(R.string.login_with_space), null);
        mEditPw.setKeyListener(new DigitsKeyListener() {
            @Override
            public int getInputType() {
                return InputType.TYPE_TEXT_VARIATION_PASSWORD;
            }

            @Override
            protected char[] getAcceptedChars() {
                char[] data = getResources().getString(
                        R.string.edit_only_can_input).toCharArray();
                return data;
            }
        });
        EventBus.getDefault().register(this);
    }

    public boolean checkData() {
        mSavePhone = mEditPhone.getText().toString().trim();
        mSavePw = mEditPw.getText().toString().trim();
        if (!StringUtils.isMobile(mSavePhone)) {
            SVProgressHUD.showInfoWithStatus(aty, getString(R.string.input_right_phone));
        } else {
            if (StringUtils.isEmpty(mSavePw) || StringUtils.isNumRic(mSavePw) || StringUtils.isLetterRic(mSavePw) || mSavePw.length() < 6 || mSavePw.length() > 18) {
                SVProgressHUD.showInfoWithStatus(aty, getString(R.string.input_right_pw));
            } else {
                return true;
            }
        }
        return false;
    }

    @OnClick({R.id.id_login_btn, R.id.id_register_txt, R.id.id_forget_pw_txt, R.id.id_login_qq_img, R.id.id_login_wx_img, R.id.id_login_sina_img})
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_login_btn:
                //登录
                if (checkData()) {
                    ((UserPresenter) presenter).login(mSavePhone, HexUtil.encodeHexStr(MD5Util.md5(mSavePw)));
                }
                break;
            case R.id.id_register_txt:
                //注册
                showActivity(aty, RegisterAty.class);
                break;
            case R.id.id_forget_pw_txt:
                //忘记密码
                showActivity(aty, ResetPwAty.class);
                break;
            case R.id.id_login_qq_img:
                //QQ登录
                if (ClickCounter.isFastClick(2000)) {
                    return;
                }
                break;
            case R.id.id_login_wx_img:
                //微信登录
                break;
            case R.id.id_login_sina_img:
                //新浪微博登录
                break;
        }
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.Login.LOGIN_SUCCESS)) {
                //登录成功
                model = (UserInfoModel) t;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SVProgressHUDDismiss();
                        SVProgressHUD.showWithStatus(aty, getString(R.string.data_loading));

                        if (null != model) {
                            //环信登录
                            imLogin();
                        } else {
                            SVProgressHUD.showInfoWithStatus(aty, getString(R.string.login_fail));
                        }
                    }
                });
            }
        }
    }

    /**
     * 登录
     */
    private void imLogin() {
        EMClient.getInstance().login("siza_"+model.ucId, model.passport, new EMCallBack() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SVProgressHUDDismiss();
                        SVProgressHUD.showSuccessWithStatus(aty, "登录成功");

                        Session.setUserIsLogin(true);
                        Session.setUserId(model.ucId);
                        Session.setUserToken(model.token);
                        Session.setUserHead(model.logoUrl);
                        Session.setUserName(model.nickName);
                        Session.setUserPhone(model.phone);
                        Session.setUserSex(model.sex);
                        Session.setUserSign(model.signature);

                        //登录成功
                        BaseEvent event = new BaseEvent();
                        event.data = IntentKey.Login.KEY_LOGIN_SUCCESS;
                        EventBus.getDefault().post(event);

                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                SVProgressHUDDismiss();
                                if (isRegister) {
                                    showActivity(aty, ChooseCompanyAty.class);
                                }
                                finish();
                            }
                        }, 2000);
                    }
                });
            }

            @Override
            public void onError(int i, final String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LogUtils.LogD("环信登录", s + "----------");
                        SVProgressHUDDismiss();
                        SVProgressHUD.showInfoWithStatus(aty, getString(R.string.login_fail));
                    }
                });
            }

            @Override
            public void onProgress(int i, String s) {
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventUpdate(final BaseEvent event) {
        String data = event.data;
        if (TextUtils.equals(data, IntentKey.Register.KEY_REGISTER_SUCCESS)) {
            isRegister = true;
            //注册成功- 登录
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    model = (UserInfoModel) event.model;
                    mEditPhone.setText(model.phone);

                    SVProgressHUDDismiss();
                    SVProgressHUD.showWithStatus(aty, getString(R.string.data_loading));
                    if (null != model) {
                        //环信登录
                        imLogin();
                    } else {
                        SVProgressHUD.showInfoWithStatus(aty, getString(R.string.login_fail));
                    }
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
